import { createStore } from "vuex";

export default createStore({
  state: {
    gridItems: Array(12)
      .fill(null)
      .map((_, index) => {
        const row = Math.floor(index / 4);
        const col = index % 4;
        return {
          content: null,
          isHighlighted: false,
          rowStart: row + 1,
          colStart: col + 1,
          rowEnd: row + 2,
          colEnd: col + 2,
        };
      }),
    draggedItem: null,
    originalPosition: null, // 记录原始位置
  },
  getters: {
    canPlaceModule: (state) => (row, col, rows, cols) => {
      let result = checkPrimaryPosition(state, row, col, rows, cols);
      if (!result.success) {
        result = checkAlternativePositions(state, row, col, rows, cols);
      }
      return result;
    },
  },
  mutations: {
    startDrag(state, module) {
      state.draggedItem = module;

      // 记录原始位置
      state.originalPosition = {
        row: Math.floor(module.index / 4),
        col: module.index % 4,
        rows: module.rows,
        cols: module.cols,
      };

      // 清空原位置的内容
      for (let r = 0; r < module.rows; r++) {
        for (let c = 0; c < module.cols; c++) {
          const idx =
            (state.originalPosition.row + r) * 4 +
            (state.originalPosition.col + c);
          if (idx >= 0 && idx < state.gridItems.length) {
            state.gridItems[idx].content = null;
          }
        }
      }
    },
    clearOriginalPosition(state, index) {
      // 清除原位置的内容
      const row = Math.floor(index / 4);
      const col = index % 4;
      for (let r = 0; r < state.draggedItem.rows; r++) {
        for (let c = 0; c < state.draggedItem.cols; c++) {
          const idx = (row + r) * 4 + (col + c);
          if (idx >= 0 && idx < state.gridItems.length) {
            state.gridItems[idx].content = null;
          }
        }
      }
    },
    dragOver(state, { newIndex }) {
      const draggedItem = state.draggedItem;
      const newRow = Math.floor(newIndex / 4);
      const newCol = newIndex % 4;

      state.gridItems.forEach((item) => (item.isHighlighted = false));

      const placementResult = this.getters.canPlaceModule(
        newRow,
        newCol,
        draggedItem.rows,
        draggedItem.cols
      );
      if (placementResult.success) {
        for (let r = 0; r < draggedItem.rows; r++) {
          for (let c = 0; c < draggedItem.cols; c++) {
            const idx =
              (placementResult.newRow + r) * 4 + (placementResult.newCol + c);
            if (idx >= 0 && idx < state.gridItems.length) {
              state.gridItems[idx].isHighlighted = true;
            }
          }
        }
      }
    },
    dropItem(state, { newIndex }) {
      const draggedItem = state.draggedItem;
      const newRow = Math.floor(newIndex / 4);
      const newCol = newIndex % 4;

      const result = this.getters.canPlaceModule(
        newRow,
        newCol,
        draggedItem.rows,
        draggedItem.cols
      );
      if (result.success) {
        placeModule(
          state.gridItems,
          result.newRow,
          result.newCol,
          draggedItem.rows,
          draggedItem.cols,
          draggedItem
        );
        state.draggedItem = null; // Reset dragged item
      } else {
        // 如果没有找到合适的位置，则恢复原位置
        restoreOriginalPosition(state);
      }

      // 清除原始位置记录
      state.originalPosition = null;
    },
    resetHighlight(state) {
      state.gridItems.forEach((item) => (item.isHighlighted = false));
    },
  },
  actions: {
    startDrag({ commit }, module) {
      commit("startDrag", module);
    },
    clearOriginalPosition({ commit }, index) {
      commit("clearOriginalPosition", index);
    },
    dragOver({ commit }, payload) {
      commit("dragOver", payload);
    },
    dropItem({ commit }, payload) {
      commit("dropItem", payload);
    },
    resetHighlight({ commit }) {
      commit("resetHighlight");
    },
  },
});

// 放置模块
function placeModule(gridItems, newRow, newCol, rows, cols, draggedItem) {
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const idx = (newRow + r) * 4 + (newCol + c);
      gridItems[idx] = {
        content: draggedItem.content,
        isHighlighted: false,
        rowStart: newRow + 1,
        colStart: newCol + 1,
        rowEnd: newRow + rows + 1,
        colEnd: newCol + cols + 1,
      };
    }
  }
}

// 恢复原始位置
function restoreOriginalPosition(state) {
  const { row, col, rows, cols } = state.originalPosition;

  // 将模块内容恢复到原始位置
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const idx = (row + r) * 4 + (col + c);
      if (idx >= 0 && idx < state.gridItems.length) {
        state.gridItems[idx].content = state.draggedItem.content;
        state.gridItems[idx].isHighlighted = false;
      }
    }
  }
}

// 检查主位置是否可以放置
function checkPrimaryPosition(state, row, col, rows, cols) {
  if (col + cols > 4 || row + rows > 3)
    return {
      success: false,
    };

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const idx = (row + r) * 4 + (col + c);
      if (
        idx >= state.gridItems.length ||
        (state.gridItems[idx] && state.gridItems[idx].content)
      )
        return {
          success: false,
        };
    }
  }

  return {
    success: true,
    newRow: row,
    newCol: col,
  };
}

// 检查替代位置是否可以放置
function checkAlternativePositions(state, row, col, rows, cols) {
  if (cols === 2 && rows === 1) {
    const leftResult = checkLeft(state, row, col, rows, cols);
    if (leftResult.success) return leftResult;
  } else if (cols === 1 && rows === 2) {
    const aboveResult = checkAbove(state, row, col, rows, cols);
    if (aboveResult.success) return aboveResult;
  } else if (cols === 2 && rows === 2) {
    const topLeftResult = checkTopLeft(state, row, col, rows, cols);
    if (topLeftResult.success) return topLeftResult;

    const leftResult = checkLeft(state, row, col, rows, cols);
    if (leftResult.success) return leftResult;

    const aboveResult = checkAbove(state, row, col, rows, cols);
    if (aboveResult.success) return aboveResult;
  }

  return {
    success: false,
  };
}

// 检查左边是否可以放置
function checkLeft(state, row, col, rows, cols) {
  if (col - 1 < 0)
    return {
      success: false,
    };

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const idx = (row + r) * 4 + (col + c - 1);
      if (
        idx >= state.gridItems.length ||
        (state.gridItems[idx] && state.gridItems[idx].content)
      )
        return {
          success: false,
        };
    }
  }

  return {
    success: true,
    newRow: row,
    newCol: col - 1,
  };
}

// 检查上面是否可以放置
function checkAbove(state, row, col, rows, cols) {
  if (row - 1 < 0)
    return {
      success: false,
    };

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const idx = (row - 1 + r) * 4 + (col + c);
      if (
        idx >= state.gridItems.length ||
        (state.gridItems[idx] && state.gridItems[idx].content.content)
      )
        return {
          success: false,
        };
    }
  }

  return {
    success: true,
    newRow: row - 1,
    newCol: col,
  };
}

// 检查左上角是否可以放置
function checkTopLeft(state, row, col, rows, cols) {
  if (row - 1 < 0 || col - 1 < 0)
    return {
      success: false,
    };

  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      const idx = (row - 1 + r) * 4 + (col + c - 1);
      if (
        idx >= state.gridItems.length ||
        (state.gridItems[idx] && state.gridItems[idx].content.content)
      )
        return {
          success: false,
        };
    }
  }

  return {
    success: true,
    newRow: row - 1,
    newCol: col - 1,
  };
}
